<?php

namespace app\common\service\Oss;

use OSS\OssClient;
use OSS\Core\OssException;
use think\Config;

class Common
{
    protected $_ossClient = null;
    protected $_endpoint = "";
    protected $_accessKeyId = "";
    protected $_accessKeySecret = "";
    protected $_bucket = "";
    
    public function __construct(){
        $this->_endpoint = Config::get("ALIYUN_OSS_ENDPOINT"); 
        $this->_accessKeyId = Config::get("ALIYUN_OSS_ID");
        $this->_accessKeySecret = Config::get("ALIYUN_OSS_SECRET");
        $this->_bucket = Config::get("ALIYUN_OSS_BUCKET");
        
        if (is_file(EXTEND_PATH.'OSS/autoload.php')) {
            require_once EXTEND_PATH.'OSS/autoload.php';
        }         

        $this->getOssClient();
    }
    
    /**
     * 切换OSS Bucket
     * @param type $bucketName
     */
    public function setBucketName($bucketName) {
        $this->_bucket = $bucketName;
    }
    
    public function getBucketName() {
        return $this->_bucket;
    }
    
    /**
     * 根据Config配置，得到一个OssClient实例
     *
     * @return OssClient 一个OssClient实例
     */
    public function getOssClient() {
        if ($this->_ossClient == NULL) {
            try {
                $this->_ossClient = new OssClient($this->_accessKeyId, $this->_accessKeySecret, $this->_endpoint, false);
            } catch (OssException $e) {
                throw_exception($e->getMessage());
                return null;
            }
        }
        return $this->_ossClient;
    }
    
}
